#include "fxcc/core/audio/common/WavFile.h"
#include "AL/al.h"

using namespace fxcc::audio::common;

bool WavFile::Init()
{

    if (m_Path.empty())
    {
        return false;
    }
    if (!fs::exists(m_Path))
    {
        return false;
    }

    std::ifstream file(m_Path, std::ios::binary);
    if (!file.is_open()) {
        
        ztclog::info("cannot open file %s", m_Path.c_str());
        return false;
    }

    file.read(reinterpret_cast<char*>(&m_Header), sizeof(WAVHeader));

    if (std::string(m_Header.chunkID, 4) != "RIFF" || std::string(m_Header.format, 4) != "WAVE") {
        ztclog::info("is not a avail wav file ");
        return false;
    }


    m_Data.resize(m_Header.subchunk2Size);
    file.read((char*)&m_Data[0], m_Header.subchunk2Size);

    file.close();

    return true;
}

WavFile::WavFile(const std::string& _p)
    :m_Path(_p), m_Desc(_p)
{
    m_Available = Init();
}

uint32_t WavFile::DataSize()
{
    return this->m_Header.subchunk2Size;
}

uint8_t* WavFile::Data()
{
    return &m_Data[0];
}

uint32_t WavFile::SampleRate()
{
    return m_Header.sampleRate;
}

uint16_t WavFile::GetAlFormat()
{
    ////0x1103
    //return AL_FORMAT_MONO16;
    //return 0x1103;

    if (m_Header.numChannels == 1) {
        return (m_Header.bitsPerSample == 8) ? AL_FORMAT_MONO8 : AL_FORMAT_MONO16;
    }
    else if (m_Header.numChannels == 2) {
        return (m_Header.bitsPerSample == 8) ? AL_FORMAT_STEREO8 : AL_FORMAT_STEREO16;
    }
    return 0;
}



WavFile::~WavFile()
{
}
